package main

import (
	"encoding/json"
	"fmt"
	"net"
	"strings"
	//"study/LiveRobot/define"
	//"study/LiveRobot/reptile"
	"robot/study/LiveRobot/define"
	"robot/study/LiveRobot/reptile"
)

func process(conn net.Conn) {
	var mm define.Message2
	defer conn.Close()
	buf := make([]byte, 1000)
	n, err := conn.Read(buf[:])
	if err != nil {
		fmt.Println("获取数据出错了", err)
	}
	var s []byte
	for i, v := range buf[:n] {
		if v == 123 {
			s = buf[i:n]
			break
		}
	}
	fmt.Println("收到数据", string(s))
	err2 := json.Unmarshal(s, &mm)
	if err2 != nil {
		fmt.Println("unmarshal失败", err2)
	}
	fmt.Println(mm)
	conn.Write([]byte("HTTP/1.1 200 OK\r\n\r\nContent-Type: text/html\r\n\r\n"))
	//--------------------------事件处理
	if mm.MessageType == "group" {
		//专治马子哥表情包
		if strings.Contains(mm.RawMessage, "[CQ:image,file") && reptile.Reb.Flag == true {
			reptile.Reb.U = &mm
			reptile.Reb.Work()
			return
		}
		//获取所有指令
		if mm.UserId != define.QQ && strings.Contains(mm.RawMessage, "[CQ:at,qq="+define.QQ_String+"]") {
			if strings.Contains(mm.RawMessage, "所有指令") {
				return
			}
			l := strings.Index(mm.RawMessage, "[CQ:at,qq="+define.QQ_String+"]")
			if mm.RawMessage[len(mm.RawMessage)-1:] == "]" {
				mm.RawMessage = mm.RawMessage[:l] + mm.RawMessage[l+21:]
			} else {
				mm.RawMessage = mm.RawMessage[:l] + mm.RawMessage[l+22:]
			}
			fmt.Println(mm.RawMessage)
			Handle(&mm) //处理信息
		}
	} else {
		Handle(&mm)
	}
}

//监听
func Mysocket() {
	listen, err := net.Listen("tcp", "127.0.0.1:5701")
	if err != nil {
		fmt.Println("服务器监听失败", err)
		return
	}
	for {
		conn, err := listen.Accept()
		if err != nil {
			fmt.Println("链接失败", err)
			continue
		}
		go process(conn)
	}
}

//处理消息
func Handle(u *define.Message2) {
	if strings.Contains(u.RawMessage, define.TRANSLATE) {
		sw := reptile.Sweet{u}
		sw.Work()
		return
	}
	if strings.Contains(u.RawMessage, define.HOT) {
		vi := reptile.Video{u}
		vi.Work()
		return
	}
	if strings.Contains(u.RawMessage, define.VIDEO) {
		reptile.SendVideo(u)
		return
	}
	if strings.Contains(u.RawMessage, define.REVIEWOFF) {
		reptile.Reb.Workoff()
		return
	}
	if strings.Contains(u.RawMessage, define.REVIEWOPEN) {
		reptile.Reb.Workopen()
		return
	}
	if strings.Contains(u.RawMessage, define.SETU) {
		ie := reptile.Image{u}
		ie.Work() //发送se图
		return
	} else {
		resa := reptile.Response{U: u}
		resa.Work()
	}
}

//func main() {
//	var wg sync.WaitGroup
//	wg.Add(1)
//	reptile.Reb = &reptile.Rebiao{ //new一个全局对象，控制表情包复读
//		Flag: true,
//	}
//	go Mysocket()
//	wg.Wait()
//	//drawing.Test()
//
//}
